# ------- test/lit.cfg - Configuration for the 'lit' test runner -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# -----------------------------------------------------------------------------

import lit
import tempfile


def inferSwiftBinaryImpl(binaryName, envVarName):
    # If the user set the variable in the environment, definitely use that.
    execPath = os.getenv(envVarName)
    if execPath:
        return execPath

    # Otherwise, see if we were passed the path to the binary using a param.
    execPath = lit_config.params.get(envVarName)
    if execPath:
        return execPath

    # Lastly, look in the path.
    return lit.util.which(binaryName, config.environment["PATH"])


# Discover the Swift binaries to use.
def inferSwiftBinary(binaryName):
    envVarName = binaryName.upper().replace("-", "_")
    execPath = inferSwiftBinaryImpl(binaryName, envVarName)

    if execPath:
        if not lit_config.quiet:
            lit_config.note("using %s: %s" % (binaryName, execPath))
    else:
        msg = "couldn't find '%s' program, try setting %s in your environment"
        lit_config.warning(msg % (binaryName, envVarName))

        # Just substitute the plain executable name, so the run line remains
        # reasonable.
        execPath = binaryName

    return execPath


config.name = "SwiftSyntax"
config.suffixes = [".swift"]
config.test_format = lit.formats.ShTest(execute_external=True)
config.test_exec_root = tempfile.gettempdir()

config.filecheck = inferSwiftBinary("FileCheck")
config.incr_transfer_round_trip = inferSwiftBinary("incr_transfer_round_trip.py")
config.lit_test_helper = inferSwiftBinary("lit-test-helper")

config.substitutions.append(
    ("%empty-directory\(([^)]+)\)", 'rm -rf "\\1" && mkdir -p "\\1"')
)
config.substitutions.append(("%FileCheck", config.filecheck))
config.substitutions.append(
    (
        "%validate-incrparse",
        "%s --temp-dir %%t --swiftsyntax-lit-test-helper %s"
        % (config.incr_transfer_round_trip, config.lit_test_helper),
    )
)
config.substitutions.append(("%lit-test-helper", config.lit_test_helper))
